Subscripts
- Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing the member elements of a collection, list, or sequence.
- You can define multiple subscripts for a single type
Subscript Syntax
- Subscripts enable you to query instances of a type by writing one or more values in square brackets after the instance name.
- Their syntax is similar to both instance method syntax and computed property syntax
- Unlike instance methods, subscripts can be read-write or read-only.
- The type of newValue is the same as the return value of the subscript.
1 | subscript(index: Int) -> Int { |
Subscript Usage
1 | var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4] |
Subscript Options
- Subscripts can take any number of input parameters, and these input parameters can be of any type. Subscripts can also return any type. Subscripts can use variadic parameters, but they can’t use in-out parameters or provide default parameter values.
- A class or structure can provide as many subscript implementations as it needs, and the appropriate subscript to be used will be inferred based on the types of the value or values that are contained within the subscript brackets at the point that the subscript is used. This definition of multiple subscripts is known as subscript overloading.
1 | struct Matrix { |